package com.cn.aam.checaiduo.ui.homepage;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.cn.aam.checaiduo.BuildConfig;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestV2Listener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.bean.UpdateInfoB;
import com.cn.aam.checaiduo.bean.base.NormalResponseB;
import com.cn.aam.checaiduo.center.CustomDialogCenter;
import com.cn.aam.checaiduo.minterface.OnTabSelectedListener;
import com.cn.aam.checaiduo.ui.arouter.UIRouter;
import com.cn.aam.checaiduo.ui.homepage.fragment.HomeFragment;
import com.cn.aam.checaiduo.ui.homepage.fragment.InvestFragment;
import com.cn.aam.checaiduo.ui.homepage.fragment.MeFragment;
import com.cn.aam.checaiduo.ui.homepage.fragment.OtherMoreFragment;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.utils.SystemUtil;
import com.cn.aam.checaiduo.widget.WMToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;

import static com.cn.aam.checaiduo.Const.INTENT_REQUEST_PARK;

@Route(path = UIRouter.HOME.AC_MAIN)
public class MainActivity extends BaseActivity {
    public int originIndex = -1;
    public int curIndex = 0;
    private List<Fragment> fragments = new ArrayList<>();
    //底部的控件
    private List<View> bomImages = new ArrayList<>();
    private List<View> bomtv = new ArrayList<>();
    private long mExitTime;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView(savedInstanceState);
    }

    public static Intent newInstance(Context context, int flag) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("park", flag);
        return intent;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        //新手乐园跳转到投资的界面
        if (intent.getIntExtra("park", -1) == INTENT_REQUEST_PARK) {
            curIndex = 1;
            originIndex = 1;
            setCurrentFragment(1);
        }
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onGenerate() {
        checkVersion();
    }

    private void initView(@Nullable Bundle savedInstanceState) {


        if (savedInstanceState != null) {
            curIndex = savedInstanceState.getInt("currentIndex");//异常推出前所在的fragment
            fragments.clear();
            //获取到已经存在的fragment,并且存放到集合中
            FragmentManager manager = getSupportFragmentManager();
            fragments.add(0, manager.findFragmentByTag(HomeFragment.class.getName()));
            fragments.add(1, manager.findFragmentByTag(InvestFragment.class.getName()));
            fragments.add(2, manager.findFragmentByTag(MeFragment.class.getName()));
            fragments.add(3, manager.findFragmentByTag(OtherMoreFragment.class.getName()));
        } else {
            initBottom();

        }

        setCurrentFragment(curIndex);
    }

    private void initBottom() {
        fragments.add(HomeFragment.newInstance());
        fragments.add(InvestFragment.newInstance());
        fragments.add(MeFragment.newInstance());
        fragments.add(OtherMoreFragment.newInstance());

        bomImages.add(myFindViewsById(R.id.main_iv_home));
        bomImages.add(myFindViewsById(R.id.main_iv_invest));
        bomImages.add(myFindViewsById(R.id.main_iv_me));
        bomImages.add(myFindViewsById(R.id.main_iv_more));

        bomtv.add(myFindViewsById(R.id.main_tv_home));
        bomtv.add(myFindViewsById(R.id.main_tv_invest));
        bomtv.add(myFindViewsById(R.id.main_tv_me));
        bomtv.add(myFindViewsById(R.id.main_tv_more));
    }


    @OnClick({R.id.main_ll_home, R.id.main_ll_invest, R.id.main_ll_me, R.id.main_ll_more})
    void clickItem(View v) {
        //重复点击
        int chooseItem = Integer.parseInt(v.getTag().toString());
        if (chooseItem == curIndex) {

            if (fragments.get(curIndex) instanceof OnTabSelectedListener && !MyViewsUtils.isFastDoubleClick()) {
                ((OnTabSelectedListener) fragments.get(curIndex)).onTabReSelected();
            }
            return;
        }
        originIndex = curIndex;
        switch (v.getId()) {
            case R.id.main_ll_home:
                curIndex = 0;
                setCurrentFragment(curIndex);
                break;
            case R.id.main_ll_invest:
                curIndex = 1;
                setCurrentFragment(curIndex);
                break;
            case R.id.main_ll_me:
                curIndex = 2;
                if (!SystemUtil.isNetworkAvailable(this)) {
                    goLogin();
                    return;
                }
                if (!needLogin()) setCurrentFragment(curIndex);
                break;
            case R.id.main_ll_more:
                curIndex = 3;
                if (!SystemUtil.isNetworkAvailable(this)) {
                    goLogin();
                    return;
                }
                if (!needLogin()) setCurrentFragment(curIndex);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Const.INTENT_REQUEST_LOGIN && resultCode == RESULT_OK) {
            setCurrentFragment(curIndex);
        }
        if (requestCode == Const.INTENT_REQUEST_LOGIN && resultCode == RESULT_CANCELED) {
            curIndex = 0;
            originIndex = 0;
            setCurrentFragment(0);
        }
        //通知当前子fragment
        fragments.get(curIndex).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            WMToast.normal("再按一次退出程序");
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putInt("currentIndex", curIndex);  //保存当前显示的fragment的索引
    }

    public void setCurrentFragment(int index) {
        curIndex = index;
        if (bomImages.size() == 0) return;

        for (int i = 0; i < bomImages.size(); i++) {
            bomImages.get(i).setActivated(false);
            bomtv.get(i).setActivated(false);
        }

        bomImages.get(index).setActivated(true);
        bomtv.get(index).setActivated(true);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(R.anim.abc_popup_enter, R.anim.abc_popup_exit);
        //隐藏所有fragment
        for (Fragment fragment : fragments) {
            transaction.hide(fragment);
        }
        Fragment currentFragment = fragments.get(index);
        if (currentFragment.isAdded()) {
            transaction.show(currentFragment);
        } else {
            String tag = currentFragment.getClass().getName();
            transaction.add(R.id.fragment_container, currentFragment, tag);
            transaction.show(currentFragment);
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 检测新版本
     */
    private void checkVersion() {
        RetrofitHome.getInstance()
                .getInternalApi()
                .checkAndroidVersion()
                .compose(RxSchedulers.<NormalResponseB<UpdateInfoB>>toMain())
                .subscribe(new OnRequestV2Listener<UpdateInfoB>(this) {
                    @Override
                    protected boolean isShowProgressBar() {
                        return false;
                    }

                    @Override
                    public void onNext(NormalResponseB<UpdateInfoB> value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_FAILED) return;
                        UpdateInfoB data = value.getData();
                        if (data.getVersion().compareTo(BuildConfig.VERSION_NAME) > 0) {
                            CustomDialogCenter.getInstance().showAppUpdate(mContext, data);
                        }
                    }
                });
    }


}
